package com.yanqu.road.server.cmd;

import com.yanqu.road.listener.DelayCloseGenericFutureListener;
import com.yanqu.road.pb.common.CommonProto;
import com.yanqu.road.pb.login.LoginProto;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.server.protocol.ClientProtocol;
import io.netty.channel.ChannelPromise;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.yanqu.road.player.Player;
import com.yanqu.road.player.PlayerControl;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.command.Command;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;

@Cmd(code = Protocol.A_LOGIN_RESPONSE, desc = "GameServer返回是否允许用户登录")
public class LoginResultCmd implements Command {

	private static Logger logger = LogManager.getLogger(Class.class.getName());

	@Override
	public void execute(ChannelHandlerContext ctx, YanQuMessage packet) throws Exception {
		LoginProto.LoginResultMsg msg = LoginProto.LoginResultMsg.parseFrom(packet.toByteArray());
		boolean result = msg.getResult();
		long userId = msg.getUserId();

		Player player = PlayerControl.getOnlinePlayer(userId);
		Channel channel = PlayerControl.removeChannelCache(userId);
		if (null == channel) {
			logger.info("Login result failed, userId = " + userId);
			return;
		}

		if (!result) {
			channel.close().sync();
			logger.info("user waite failed,userId = " + userId);
			return;
		}

		try {
			if (null != player && player.getAgentServerConnection() != null) {
				Channel ch = player.getChannel();
				try {
					ch.writeAndFlush(YanQuMessageUtils.buildMessage(ClientProtocol.U_OTHER_LOGIN_YOUR_ROLE, player.getPlayerId(), CommonProto.NullValueMsg.newBuilder()),
							newPromise(ch));
				} catch (Exception ex) {
					logger.error(ex);
				}

		//		player.closeChannel();
			}
		} catch (Exception e) {
			logger.error("Disconnect userId = " + player.getPlayerId());
		}

		PlayerControl.addPlayerOnline(userId, channel);
	}

	private ChannelPromise newPromise(Channel channel) {
		ChannelPromise promise = channel.newPromise();
		promise.addListener(new DelayCloseGenericFutureListener(channel).getListener());
		return promise;
	}
}
